Skip to content

Use split-KV lane attention for FP16-cache decode on Metal (Granite, Llama Q8_0/Q4_0, 64-wide heads) - #291

Merged
orionpapadakis merged 6 commits into
mainfrom
perf/metal-split-kv-decode-attention
Dec 1, 2026
Merged

orionpapadakis merged 6 commits into
mainfrom
perf/metal-split-kv-decode-attention

Conversation

@stratika

@stratika stratika commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

On Metal, FP16-KV-cache decode fell back to the one-workgroup-per-head attention kernel in three places, so decode slowed sharply with context depth. Each fix routes decode to the existing split-KV lane-cooperative kernel (followed by combineSplitKVAttention). No new kernels.

Model (M4 Pro) Decode at depth 2048, tok/s Cause
Granite-4.0-1B F16 4.2 → 52.3 Granite's FP16 layers never used the scaled lane kernel
Llama-3.2-3B Q8_0 5.7 → 43.9 (FP32 KV: 41–42) attentionSplits() returned 0 on every non-NVIDIA device
Llama-3.2-1B F16 / Q8_0 35.8 → 83.8 / 40.8 → 111.4 LaneAttentionPolicy allowed only 128-wide heads on Metal

Depth 0 does not regress: Granite 52.1 → 55.9, Llama-3B 39.5 → 47.2, Llama-1B F16 87.6 → 89.8, Q8_0 119.9 → 122.0. These numbers come from a defaults sweep in which the FP16 KV cache was 2–10× slower than FP32 KV at depth on these models. After this change FP16 KV is as fast or faster on every model tested.

Changes

  • GraniteFP16FFNLayers / GraniteFP16FFNLayersDecode:
    • When the FP16 cache isn't packed half2 and the policy allows the scaled lane kernel, run LaneAttentionPolicy.scaledKernel with State.SPLIT_KV splits and then the combine.
    • Bind wrapAttSplit in the prefill and decode graphs.
  • LlamaQ8_0FFNLayers.attentionSplits() (Llama Q8_0 and Q4_0):
    • Off NVIDIA, split where the lane kernel runs.
    • Keep 0 elsewhere, because the per-key FP16 split kernel exceeds Metal's 32 KB of threadgroup memory.
  • LaneAttentionPolicy:
    • Allow the 64-wide kernel on Metal: the same 32-lane shuffles as the 128-wide one, with 4 KB of threadgroup memory.
    • The 96-wide kernel stays off because it hasn't been verified on Metal.
  • AbstractTransformerLayerTaskGraphs.laneAttention(headSize, policy): the FP16-cache and packed-half2 conditions in one place. Granite FP16 and Q8_0 pass the scaled policy instead of keeping their own copies.
  • New GpuFp16KvLlama3BAccelTest: Llama-3.2-3B Q8_0 and Q4_0 (128-wide heads). The 1B fixtures cover the 64-wide kernel.
  • LaneAttentionAccelTest:
    • Also checks the scaled kernels (64 and 128) against the host reference, with Granite 3.x's multiplier 1/64.
    • Keeps every TornadoVM type in a nested class, so surefire can load it under -Paccel-tests. Surefire looks for a JUnit 3 suite() in Maven's own JVM, where TornadoVM isn't on the class path, and stopped the run with NoClassDefFoundError: TornadoFunctions$Task15.

Testing

  • ./mvnw test: 980 tests, 0 failures.

  • -Paccel-tests, FP16 vs FP32 KV on the GPU (~300-token prompt, 24 decode steps), on TornadoVM 8.2.0 Metal (M4 Pro). Single-token and batched prefill each; the lower minimum cosine of the two is shown, and top-1 agreement is 1.0 everywhere:

    Test Model (head width) Minimum cosine
    GpuFp16KvLlamaF16AccelTest Llama-3.2-1B F16 (64) 0.9999992
    GpuFp16KvLlamaQ8AccelTest Llama-3.2-1B Q8_0 (64) 0.9999995
    GpuFp16KvLlama3BAccelTest Llama-3.2-3B Q8_0 (128) 0.9999988
    GpuFp16KvLlama3BAccelTest Llama-3.2-3B Q4_0 (128) 0.9999992
    GpuFp16KvGranite4F16AccelTest Granite-4.0-1B F16 (128) 0.9999998
    GpuFp16KvGraniteF16AccelTest Granite 3.2 2B F16 (64) 0.9999987
    GpuFp16KvGraniteQ8AccelTest Granite 3.2 2B Q8_0 (64) 0.9999991
    GpuFp16KvQwen2F16AccelTest Qwen2.5-0.5B F16 (64) 0.9999975
    GpuFp16KvQwen2Q8AccelTest Qwen2.5-0.5B Q8_0 (64) 0.9999979
  • Lfm2Fp16KvParityAccelTest on LFM2-8B-A1B (64-wide): CPU/GPU, prefill-decode and batched parity pass (minimum cosine 0.9983 against a 0.996 bound, argmax 63/63). The native-path cases skip, because they need tensor cores.

  • LaneAttentionAccelTest under surefire on Metal, sequence lengths 1 to 2048: plain 64 and 128 and scaled 64 and 128 pass (worst relative L2 7.3e-7). 96-wide skips, as it isn't enabled on Metal.

  • Greedy decode of 120 tokens after a ~2,100-token prompt is identical to the FP32 cache for Granite-4.0-1B F16, Llama-3.2-3B Q8_0 and Llama-3.2-1B F16/Q8_0.

Not covered

  • CI: the self-hosted runners were offline when this was opened, so the first run was cancelled after 24 hours in the queue. Nothing here has run on CUDA or OpenCL yet.
  • The Q4_0 3B fixture: it is quantized locally from the F16 file with llama-quantize. It skips where absent, like the other fixtures.
  • Granite's FP32-cache path: unchanged, because no scaled FP32 lane kernel exists.
  • LlamaBatchedPrefillParityAccelTest.llama3_2_1b_q8_0_batchedPrefillParity: fails both with and without this change, with 0.075% of elements over tolerance and the argmax agreeing. That failure is pre-existing.

Granite's FP16 layers kept the one-workgroup-per-head attention kernel
for decode, which costs time linear in the context with only one
workgroup per head. On an M4 Pro, Granite-4.0-1B F16 spent 5.1 ms per
layer in it at depth 2048, 92% of decode, and decoded at 4.2 tok/s.

Where LaneAttentionPolicy allows the scaled lane-cooperative kernel and
the cache is FP16 (not packed half2), run it with State.SPLIT_KV splits
and combineSplitKVAttention, and bind the split scratch buffer in the
prefill and decode graphs.

Granite-4.0-1B F16 decode on an M4 Pro: 4.2 -> 52.3 tok/s at depth 2048,
52.1 -> 55.9 at depth 0. FP16 vs FP32 KV: minimum cosine 0.9999998,
top-1 agreement 1.0; 120 greedy tokens after a 2,100-token prompt match
the FP32 cache. The FP32-cache path is unchanged (no scaled FP32 lane
kernel exists).
attentionSplits() returned 0 on every non-NVIDIA device, so on Metal
Llama Q8_0 and Q4_0 decoded with the one-workgroup-per-head kernel even
where the lane-cooperative split kernel runs. Llama-3.2-3B Q8_0 on an
M4 Pro decoded at 4.6-5.7 tok/s at depth 2048, 87% of it in that kernel.

Off NVIDIA, split where LaneAttentionPolicy allows the lane kernel; keep
0 elsewhere, since the per-key FP16 split kernel needs more threadgroup
memory than Metal allows.

Llama-3.2-3B Q8_0 decode on an M4 Pro: 5.7 -> 43.9 tok/s at depth 2048
(FP32 KV: 41-42), 39.5 -> 47.2 at depth 0. Add GpuFp16KvLlama3BQ8AccelTest,
since the 1B fixtures have 64-wide heads and never reached this path:
minimum cosine 0.999999, top-1 agreement 1.0.
LaneAttentionPolicy allowed only the 128-wide lane-cooperative kernel on
Metal, so models with 64-wide heads kept the one-workgroup-per-head
decode attention. Llama-3.2-1B on an M4 Pro spent 1.0 ms per layer in
it at depth 2048, 60% of decode. The 64-wide kernel uses the same
32-lane shuffles as the 128-wide one and 4 KB of threadgroup memory.
The 96-wide kernel stays off on Metal: it has not been verified there.

Llama-3.2-1B decode at depth 2048 on an M4 Pro: F16 35.8 -> 83.8 tok/s,
Q8_0 40.8 -> 111.4. LaneAttentionAccelTest (64-wide, lengths 1..2048):
worst relative L2 2.6e-7. GpuFp16KvLlamaF16/Q8 pass, minimum cosine
0.9999992; greedy output matches the FP32 cache.

This also enables the split for other families with 64-wide heads on
Metal (Qwen2-0.5B, LFM2, Granite Q8_0), which were not run end to end.

@orionpapadakis orionpapadakis left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, contained change: it adds no kernels, and on Llama the split count, worker grid and kernel choice all key off the same laneAttention(headSize), so they can't disagree. I checked that GraniteState already sizes wrapAttSplit as heads * SPLIT_KV * (headSize + 2), so the Granite path has its scratch.

Main ask is in the inline comment on LaneAttentionPolicy: the 64-wide change reaches families that weren't tested on Metal. Also, since LaneAttentionAccelTest currently only runs outside surefire, please link the issue for that so the 64-wide kernel check is repeatable. The LlamaBatchedPrefillParityAccelTest failure is pre-existing and not a blocker here.

Comment on lines +869 to +873
// Off NVIDIA, the FP16 cache splits only where the lane-cooperative kernel runs (Metal,
// 128-wide heads): the per-key FP16 split kernel needs more threadgroup memory than Metal
// allows. Without the split, Llama-3.2-3B Q8_0 on an M4 Pro decoded at 4.6 tok/s at depth
// 2048, 87% of it in the one-workgroup-per-head kernel.
if (schedulerType != SchedulerType.NVIDIA && !laneAttention(config.headSize())) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"(Metal, 128-wide heads)" is out of date after fd39423, since 64-wide heads split too now. The method javadoc above (~L856–860) still says the FP16 split is "taken by default on the NVIDIA path". It's now the default wherever laneAttention(headSize) holds, so please update both. Same nit as in the policy class about the tok/s figures in the comment.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3af0283. The javadoc now says the FP16 cache splits by default wherever laneAttention(headSize) holds, on any backend, and otherwise only on NVIDIA when asked for; the inline comment no longer names a width and has no tok/s.

Comment on lines +426 to +430
// Split-KV with the lane-cooperative kernel, scored by Granite's attention multiplier
// rather than 1/sqrt(headSize); the combine pass merges the partials. The flash kernel
// below runs one workgroup per head and walks the whole context in 16-key tiles,
// so its cost grows linearly with depth on a handful of workgroups: on an M4 Pro,
// Granite-4.0-1B F16 spent 5.1 ms per layer in it at depth 2048 (92% of decode).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the M4 Pro timing again. The first sentence is enough.

Which head width does GpuFp16KvGranite4F16AccelTest exercise here? If Granite-4.0-1B is 128-wide, then processHeadsFlashAttentionSplitKVFP16PagedLaneHead64Scaled on Metal is only covered by a kernel test (or not at all, if LaneAttentionAccelTest only checks the unscaled kernels). A 64-wide Granite fixture, e.g. 3.x 2B, would close that gap.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Timing removed in 3af0283. Granite-4.0-1B is 128-wide (2048 / 16 heads), so you were right that the 64-wide scaled kernel had no end-to-end test. Now it has two:

  • GpuFp16KvGraniteF16AccelTest and GpuFp16KvGraniteQ8AccelTest on Granite 3.2 2B (64-wide), on Metal: min cosine 0.9999987 or better, top-1 1.0.
  • LaneAttentionAccelTest also runs the scaled kernels at 64 and 128 against the host reference, with Granite 3.x's multiplier 1/64 (worst relative L2 1.2e-7 at 64, 9.3e-8 at 128 on Metal).

// @formatter:on

/** Whether attention runs the scaled lane-cooperative split-KV kernel. */
protected boolean laneAttention() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this copies AbstractTransformerLayerTaskGraphs.laneAttention(int) except for the scaled policy call. That's fine for now, but the two copies can drift apart if the packed-half2 condition ever changes. A base-class variant that takes the policy predicate would keep them in one place.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3af0283: AbstractTransformerLayerTaskGraphs.laneAttention(int headSize, IntPredicate kernelFor) holds the FP16-cache and packed-half2 conditions, and laneAttention(int) passes LaneAttentionPolicy::laneCooperativeAttention. GraniteFP16FFNLayers and GraniteQ8_0FFNLayers (which had a second copy) pass LaneAttentionPolicy::scaledLaneCooperativeAttention.

* lane-cooperative kernel on Metal as well as NVIDIA. The 1B fixtures have 64-wide heads and never
* reach that kernel on Metal.
*/
public class GpuFp16KvLlama3BQ8AccelTest {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The title covers Q4_0 too, but only the Q8_0 3B file is tested. Either add a Q4_0 3B case here, or note in the PR that Q4_0 goes through the same attentionSplits() path and wasn't run.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 3af0283: the class is now GpuFp16KvLlama3BAccelTest with Q4_0 3B single-token and batched cases. On Metal: min cosine 0.9999992 for both, top-1 1.0. The fixture (Llama-3.2-3B-Instruct-Q4_0.gguf) is quantized from the F16 file with llama-quantize; it skips where absent, like the other fixtures.

- LaneAttentionAccelTest also checks the scaled kernels (Granite's
  attention multiplier) at 64 and 128, and keeps every TornadoVM type in
  a nested class, so surefire can load it under -Paccel-tests. Surefire
  looks for a JUnit 3 suite() in Maven's own JVM, where TornadoVM is not
  on the class path, and failed with NoClassDefFoundError
  TornadoFunctions$Task15 before any test ran.
- The 3B Llama test covers Q4_0 as well as Q8_0 and is renamed
  GpuFp16KvLlama3BAccelTest.
- laneAttention(headSize, policy) in the base class; Granite FP16 and
  Q8_0 use it with the scaled policy instead of their own copies.
- Comments: no device timings, and the split-KV javadoc and comment in
  LlamaQ8_0FFNLayers describe the default on any backend and both widths.
@stratika

stratika commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Two points from the review that I didn't answer directly:

  • Qwen3 batch-prefill classes: they aren't affected by the 64-wide change. Every Qwen3 model uses 128-wide heads (qwen3.attention.key_length = 128 in Qwen3-0.6B and Qwen3-4B), and 128-wide heads already took the lane kernel on Metal before this PR.
  • LaneAttentionAccelTest only running outside surefire: fixed in 3af0283 instead of filing an issue. Surefire checks for a JUnit 3 suite() in Maven's own JVM, where TornadoVM isn't on the class path, so it failed with NoClassDefFoundError: TornadoFunctions$Task15. The test now keeps every TornadoVM type in a nested Device class. It runs under -Paccel-tests like the other accel tests, with plain and scaled kernels at 64 and 128 wide for sequence lengths 1 to 2048.

CI passes on every backend: CUDA, OpenCL and Metal builds, native images and standalone inference.

@orionpapadakis
orionpapadakis merged commit debb688 into main Dec 1, 2026
32 of 33 checks passed
@stratika
stratika deleted the perf/metal-split-kv-decode-attention branch December 1, 2026 14:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants